﻿using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class CameraFollow : MonoBehaviour
{
	public GameObject mainRole;
	public Vector3 distance = new Vector3(0, 7, -4);
	public Vector3 rotation = new Vector3(54, 0, 0);
    public Quaternion quater;

	public float sensitivityX = 8F;
	public float sensitivityY = 8F;

	float mHdg = 0F;
	float mPitch = 20F;
	private GameObject mainCamera;
    
	void Start()
	{
        quater = Quaternion.Euler(rotation);
        mainCamera = Camera.main.gameObject;//GameObject.FindGameObjectWithTag("MainCamera");
		UpdateCamera();
	}

	/// <summary>
	/// 以宿主为中心，更新摄像机位置
	/// </summary>
	public void UpdateCamera()
	{
		Camera.main.transform.position = mainRole.transform.position + distance;
        Camera.main.transform.rotation = quater;
	}

	void MoveForwards(float aVal)
	{
		Vector3 fwd = transform.forward;
		fwd.y = 0;
		fwd.Normalize();
		mainCamera.transform.position += aVal * fwd;
	}

	void Strafe(float aVal)
	{
		mainCamera.transform.position += aVal * transform.right;
	}

	void ChangeHeight(float aVal)
	{
		mainCamera.transform.position += aVal * Vector3.up;
	}

	void ChangeHeading(float aVal)
	{
		mHdg += aVal;
		WrapAngle(ref mHdg);
		mainCamera.transform.localEulerAngles = new Vector3(30, mHdg, 0);
	}

	void ChangePitch(float aVal)
	{
		mPitch += aVal;
		WrapAngle(ref mPitch);
		mainCamera.transform.localEulerAngles = new Vector3(mPitch, mHdg, 0);
	}

	public static void WrapAngle(ref float angle)
	{
		if (angle < -360F)
			angle += 360F;
		if (angle > 360F)
			angle -= 360F;
	}

}
